import Vue from 'vue'
import Vuex from 'vuex'
import {config} from '@/common/config.js'
import device from '@/common/device.js'
Vue.use(Vuex)

let limeSchool = {};

try{
	// 尝试获取本地是否存在limeSchool变量，第一次启动APP时是不存在的
	limeSchool = uni.getStorageSync('limeSchool');
}catch(e){
	
}

//判断打开的应用场景
// var product = Vue.prototype.Device //设置应用的平台

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['Device','YbCode','AppCode',"Company","Token","TokenExpire","Userinfo",'Product',"ProductInfo"];

// 保存变量到本地存储中
const savelimeSchool = function(key, value){
	// 判断变量名是否在需要存储的数组中
	if(saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的limeSchool对象，将变量添加到对象中
		let tmp = uni.getStorageSync('limeSchool');
		// 第一次打开APP，不存在limeSchool变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的limeSchool对象中
		uni.setStorageSync('limeSchool', tmp);
	}
}
const store = new Vuex.Store({
	
	// 下面这些值仅为示例，使用过程中请删除
	state: {
		uploadUrl:config.baseUrl+"/api/auth/uploadFile",
		Userinfo:limeSchool.Userinfo?limeSchool.Userinfo:'',
		vuex_version: '1.0.1',
		cosUrl:config.cos.baseUrl,
		Device:limeSchool.Device ? limeSchool.Device : Vue.prototype.Device,
		Product:limeSchool.Product ? limeSchool.Product : '',
		Company:limeSchool.Company ? limeSchool.Company : '',
		Token:limeSchool.Token ? limeSchool.Token : '',
		TokenExpire:limeSchool.TokenExpire ? limeSchool.TokenExpire : '',
		YbCode:limeSchool.YbCode ? limeSchool.YbCode : '',
		AppCode:limeSchool.AppCode ? limeSchool.AppCode : '',
		vuex_tailor:config.cos.tailor,
		ProductInfo:limeSchool.ProductInfo ? limeSchool.ProductInfo : '',//学校的相关信息
	},
	mutations: {
		resetState (state) {
			var clearArr = ["YbCode","AppCode", "Token", "TokenExpire", "Userinfo"];
			for(let i in clearArr){
				state[clearArr[i]] = null;
				delete limeSchool[clearArr[i]]
				// uni.removeStorageSync(clearArr[i]);
			}
			uni.setStorageSync('limeSchool', limeSchool);
		},
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if(nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for(let i = 1; i < len - 1; i ++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况 qps 
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			savelimeSchool(saveKey, state[saveKey])
		}
	},
	getters:{
		Company:state=>state.Company,
		Token:state=>state.Token,
		TokenExpire:state=>state.TokenExpire,
		YbCode:state=>state.YbCode,
		Product:state=>state.Product,
		AppCode:state=>state.AppCode,
		Device:state=>state.Device,
	}
})

export default store